<template>
  <view class="order-container">
    <!-- 顶部 tab 栏 -->
    <view class="tab-bar">
      <div class="search-container">
        <div class="search-box">
          <text class="search-icon">🔍</text>
          <input
            type="text"
            class="search-input"
            placeholder="请输入供应商信息或手机号搜索"
            placeholder-class="placeholder"
            confirm-type="search"
            @blur="searchOrder"
            clearable
          />
        </div>
      </div>
      <scroll-view
        scroll-x
        class="scroll-view"
        :scroll-left="scrollLeft"
        show-scrollbar="false"
      >
        <view class="tab-content">
          <view
            v-for="(item, index) in tabs"
            :key="index"
            class="tab-item"
            :class="{ active: currentTab === item.id }"
            @tap="switchTab(item.id, index)"
          >
            {{ item.name }}
            <view class="active-line" v-if="currentTab === item.id"></view>
          </view>
        </view>
      </scroll-view>
    </view>
    <cancelReason ref="cancelReasonRef" @readyCancel="readyCancel" />
    <!-- 订单列表区域 -->
    <scroll-view class="order-list" scroll-y @scrolltolower="loadMore">
      <div v-if="orderList.length === 0" class="empty-order">
        <gui-image
          src="https://cdn.duyumy.com/accessory/0fe61301ec884459440a85e2fcd72d1ae98c46da.png"
        ></gui-image>
        <div style="font-size: 28rpx; color: #999; margin-top: -20rpx">
          暂无订单~
        </div>
      </div>
      <view
        class="order-item"
        v-for="(order, index) in orderList"
        :key="index"
        @click="orderDetail(order)"
      >
        <!-- 订单头部 -->
        <view class="order-header">
          <view class="shop-info">
            <image
              class="shop-icon"
              mode="fill"
              :src="order.supplierInfo?.logo"
            ></image>
            <text class="shop-text">{{ order.supplierInfo?.name }}</text>
            <view
              class="payment-status"
              :class="[
                settle_payment_status_list[order?.settle_payment_status]?.class,
              ]"
            >
              <view class="status-dot"></view>
              <text>{{
                settle_payment_status_list[order?.settle_payment_status]?.name
              }}</text>
            </view>
          </view>
          <view class="order-toggle-box">
            <text
              class="order-status"
              :style="{ color: tabs[order.order_status]?.color }"
              >{{ order.order_status_desc }}</text
            >
            <!-- 商品列表展开/收起按钮 -->
            <div
              class="product-toggle"
              @click.stop="order.expanded = !order.expanded"
            >
              <span></span>
              <span
                class="toggle-icon"
                :class="{ 'is-expanded': order.expanded }"
              >
                {{ order.expanded ? "收起" : "展开" }}
              </span>
            </div>
          </view>
        </view>

        <!-- 订单商品 -->

        <view v-show="order.expanded">
          <view
            class="goods-item"
            v-for="(goods, goodsIndex) in order.order_detail"
            :key="goodsIndex"
          >
            <view class="goods-info">
              <view class="goods-name">{{ goods.product_name }}</view>
              <view class="goods-name">{{ goods.goods_name }}</view>
              <view class="goods-spec"
                >规格：{{ goods.goods_spec_value_name }}</view
              >
              <view class="goods-spec" style="margin-top: 10rpx"
                ><text class="goods-price">¥{{ goods.price }}</text></view
              >
            </view>
            <view class="goods-right">
              <text class="goods-count">x{{ goods.quantity }}</text>
            </view>
          </view>
        </view>

        <!-- 订单底部 -->
        <view class="order-footer">
          <view class="total-info">
            下单时间：
            <text>{{ order.create_time }}</text>
          </view>
          <view class="total-info">
            共{{
              order.order_detail &&
              order.order_detail
                .map((item) => item.quantity)
                .reduce((a, b) => a + b, 0)
            }}件商品 合计：
            <text class="total-price">¥ {{ order.pay_amount }}</text>
          </view>
          <view class="order-btnbox">
            <view
              class="order-btn"
              @click.stop="cancel(order.id)"
              v-if="order.order_status < 4"
              >取消</view
            >
            <view
              class="order-btn send"
              @click.stop="receive(order.id)"
              v-if="order.order_status == 3"
              >确认收货</view
            >
            <view
              class="order-btn send"
              @click.stop="confirmOrderData(order.id)"
              v-if="order.order_status === 1"
            >
              确定采购单
            </view>
          </view>
        </view>
      </view>
      <view style="height: 100rpx"></view>
    </scroll-view>
    <!-- 底部固定按钮 -->
    <view class="bottom-btn">
      <button class="add-purchase-btn" @click="add">新增采购</button>
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue";
import {
  getOrderList,
  confirmReceipt,
  cancelOrder,
  confirmOrder,
  getKeyforOrder,
} from "@/apiShop/order";
import { onShow } from "@dcloudio/uni-app";
import { showToast } from "@/utils/helper";
import cancelReason from "@/component/cancelReason.vue";
import { tabsList } from "@/utils/const";
const tabs = ref(tabsList);
const currentTab = ref(0);
const scrollLeft = ref(0);
const cancelReasonRef = ref(null);

const settle_payment_status_list = ref({
  1: {
    name: "未结款",
    class: "",
  },
  2: {
    name: "已结款",
    class: "paid",
  },
  3: {
    name: "已退款",
    class: "refund",
  },
});
// 修改 switchTab 方法
const switchTab = (index, scIndex) => {
  currentTab.value = index;
  // 计算滚动位置，使选中的 tab 居中
  scrollLeft.value = (scIndex - 1) * 100;
  // 这里添加你的数据加载逻辑
  orderList.value.length = 0;
  query.value.page = 1;
  query.value.order_status = index;
  getList();
};
// 页面页码多的时候刷新更新整个块面，适用于页面数据量大的情况 又得刷新下发数据
const refreshDataToMorePage = async () => {
  let oldPage = query.value.page;
  query.value.limit = 10 * query.value.page;
  query.value.page = 1;
  const res = await getOrderList(query.value);
  res.data = res.data.map((item) => ({ ...item, expanded: false }));
  orderList.value = res.data;
  query.value.page = oldPage;
  query.value.limit = 10;
};
// 加载更多
const loadMore = () => {
  // 这里可以添加加载更多数据的逻辑
  query.value.page++;
  getList("loadMore");
};
const query = ref({
  order_status: "",
  supplier_info:'',
  page: 1,
  limit: 10,
});
const confirmOrderData = (id) => {
  uni.showModal({
    title: "提示",
    content: "确定要确认此采购单吗？",
    success: (res) => {
      if (res.confirm) {
        confirmOrder({ id }).then(async () => {
          // 添加确认逻辑
          await refreshDataToMorePage();
          showToast("采购单确认成功");
        });
      }
    },
  });
};

const receive = (id) => {
  uni.showModal({
    title: "提示",
    content: "你确定已经收到货了吗？",
    success: async function (res) {
      if (res.confirm) {
        await confirmReceipt({ id });
        await refreshDataToMorePage();
        showToast("收货成功");
      }
    },
  });
};
const orderList = ref([]);
const getList = async (type = "init") => {
  const res = await getOrderList(query.value);
  res.data = res.data.map((item) => ({ ...item, expanded: false }));
  if (res.data.length === 0) return showToast("没有更多数据了");
  if (type === "init") return (orderList.value = res.data);
  orderList.value = [...orderList.value, ...res.data];
};
const currentOrderId = ref(null);

const cancel = (id) => {
  currentOrderId.value = id;
  cancelReasonRef.value.show();
};

const readyCancel = async (str) => {
  await cancelOrder({ id: currentOrderId.value, reason: str });
  await refreshDataToMorePage();
  showToast("取消成功");
};
const add = () => {
  uni.navigateTo({
    url: "/pagesShop/order/addOrder",
  });
};
const orderDetail = (order) => {
  uni.navigateTo({
    url: "/pagesShop/order/orderInfo?id=" + order.id,
  });
};

const searchOrder = async (e) => {
  query.value.page = 1;
  query.value.supplier_info = e.detail.value || ''
  const res = await getKeyforOrder(query.value);
  res.data = res.data.map((item) => ({ ...item, expanded: false }));
  orderList.value = res.data;
};
onShow(async () => {
  getList();
});
</script>

<style lang="scss" scoped>
.order-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.order-list {
  height: 100%;
  margin-top: 190rpx;
  margin-bottom: 120rpx; // 底部按钮的高度

  .order-item {
    background-color: #fff;
    border-radius: 12rpx;
    border-bottom: 10rpx solid #eee;

    .order-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 20rpx;
      padding: 40rpx;
      border-bottom: 1px solid #eee;

      .shop-info {
        display: flex;
        align-items: center;

        .shop-icon {
          width: 32rpx;
          height: 32rpx;
          margin-right: 10rpx;
        }

        .shop-text {
          font-size: 28rpx;
          color: #333;
        }
      }

      .order-status {
        font-size: 28rpx;
        color: #3399ff;
      }
    }

    .goods-item {
      display: flex;
      justify-content: space-between;
      padding: 20rpx 40rpx;

      .goods-info {
        flex: 1;

        .goods-name {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 10rpx;
        }

        .goods-spec {
          font-size: 24rpx;
          color: #999;
        }
      }

      .goods-right {
        text-align: right;

        .goods-count {
          font-size: 26rpx;
          color: #666;
          margin-right: 20rpx;
        }
      }
    }
    .goods-price {
      font-size: 28rpx;
      color: #ff0000;
    }

    .order-footer {
      display: flex;
      justify-content: end;
      align-items: center;
      padding: 40rpx;
      // border-top: 1px solid #eee;
      flex-direction: column;
      gap: 20rpx;

      .total-info {
        font-size: 26rpx;
        color: #666;
        margin-left: auto;

        .total-price {
          color: #ff0000;
          font-weight: bold;
        }
      }
      .order-btnbox {
        margin-left: auto;
        display: flex;
        gap: 20rpx;
      }
      .order-btn {
        padding: 10rpx 30rpx;
        border: 1px solid #ddd;
        border-radius: 10rpx;
        font-size: 26rpx;
        color: #666;
      }
      .send {
        border: 1px solid #69b5ff;
        color: #69b5ff;
      }
    }
  }
}

.bottom-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background-color: #fff;
  // box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  .add-purchase-btn {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background-color: #3399ff;
    color: #fff;
    font-size: 30rpx;
    border-radius: 40rpx;
    border: none;
  }
}

.tab-bar {
  background-color: #fff;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;

  .scroll-view {
    white-space: nowrap;
    width: 100%;
    height: 88rpx;
    background: #fff;

    &::-webkit-scrollbar {
      display: none;
      width: 0;
      height: 0;
      color: transparent;
    }
  }

  .tab-content {
    display: inline-flex;
    padding: 0 20rpx;
  }

  .tab-item {
    position: relative;
    display: inline-block;
    padding: 0 30rpx;
    line-height: 84rpx;
    font-size: 30rpx;
    color: #666;
    text-align: center;

    &.active {
      color: #3399ff;
      font-weight: 500;

      .active-line {
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 4rpx;
        background: #3399ff;
        border-radius: 2rpx;
      }
    }
  }
}

.cancel-popup {
  .popup-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 999;
  }

  .popup-content {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #fff;
    border-radius: 20rpx 20rpx 0 0;
    z-index: 1000;

    .popup-header {
      position: relative;
      padding: 30rpx;
      text-align: center;
      font-size: 32rpx;
      border-bottom: 1px solid #eee;

      .close-icon {
        position: absolute;
        right: 30rpx;
        top: 50%;
        transform: translateY(-50%);
        font-size: 40rpx;
        color: #999;
        padding: 0 20rpx;
      }
    }

    .popup-body {
      padding: 20rpx 30rpx;
      max-height: 60vh;
      overflow-y: auto;

      .reason-item {
        display: flex;
        align-items: center;
        padding: 30rpx 0;
        border-bottom: 1px solid #f5f5f5;

        &:last-child {
          border-bottom: none;
        }

        radio {
          transform: scale(0.8);
          margin-right: 20rpx;
        }

        text {
          font-size: 28rpx;
          color: #333;
        }
      }
    }

    .popup-footer {
      padding: 20rpx 30rpx 40rpx;

      .confirm-btn {
        width: 100%;
        height: 88rpx;
        line-height: 88rpx;
        text-align: center;
        background-color: #3399ff;
        color: #fff;
        font-size: 32rpx;
        border-radius: 44rpx;
        border: none;
      }
    }
  }
}
.empty-order {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
  flex-direction: column;
}
.payment-status {
  display: flex;
  align-items: center;
  padding: 6rpx 16rpx;
  border-radius: 24rpx;
  background: #f5f5f5;
  font-size: 24rpx;
  color: #999;
  transition: all 0.3s ease;
  margin-left: 10rpx;

  &.paid {
    background: rgba(82, 196, 26, 0.1);
    color: #52c41a;
    margin-left: 10rpx;
    text {
      font-size: 24rpx;
      color: #52c41a;
    }
  }
  &.refund {
    background: rgb(255 0 0 / 55%);
    color: #dcd5d5;
    margin-left: 10rpx;
    text {
      font-size: 24rpx;
      color: #fff;
    }
  }

  .status-dot {
    width: 12rpx;
    height: 12rpx;
    border-radius: 50%;
    background: currentColor;
    margin-right: 8rpx;
  }
}
.order-toggle-box {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  /* 商品展开/收起按钮样式 */
  .product-toggle {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;
    font-size: 26rpx;
    color: #666;
    cursor: pointer;
  }

  .toggle-icon {
    color: #1989fa;
    font-size: 24rpx;
    display: flex;
    align-items: center;
  }

  .toggle-icon.is-expanded::after {
    content: "▲";
    font-size: 20rpx;
    margin-left: 6rpx;
  }

  .toggle-icon:not(.is-expanded)::after {
    content: "▼";
    font-size: 20rpx;
    margin-left: 6rpx;
  }
}

.search-container {
  padding: 20rpx;
  background-color: #fff;
  .search-box {
    display: flex;
    align-items: center;
    height: 72rpx;
    background-color: #f5f5f5;
    border-radius: 36rpx;
    padding: 0 30rpx;
    .search-icon {
      font-size: 32rpx;
      color: #999;
      margin-right: 10rpx;
    }
    .search-input {
      flex: 1;
      height: 72rpx;
      font-size: 28rpx;
      color: #333;
      background-color: transparent;
    }

    .placeholder {
      color: #999;
      font-size: 28rpx;
    }
  }
}
</style>
